﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Sharp.Infrastructure.WebApiClient
{
    public class OAuthKit
    {
        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="clientSecret"></param>
        /// <returns></returns>
        public static async Task<string> GetAuthorizationCode(string clientId, string clientSecret)
        {
            #region 获取AccessToken

            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Basic",
                Convert.ToBase64String(Encoding.UTF8.GetBytes(clientId + ":" + clientSecret)));

            var postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            HttpContent content = new FormUrlEncodedContent(postData);


            HttpResponseMessage response = await httpClient.PostAsync("http://serv.abc.com/oauth2/token", content);

            var formcontent = await response.Content.ReadAsStringAsync();
            try
            {
                var result = JsonConvert.DeserializeObject<CallBackResult>(formcontent);
                if (!string.IsNullOrEmpty(result.Error))
                {
                    throw new NotImplementedException(result.Error);
                }

                if (string.IsNullOrEmpty(result.AccessToken))
                {
                    throw new NotImplementedException("没有获取得到 AccessToken。");
                }



                #endregion

                return result.AccessToken;
            }
            catch
            {
                throw new Exception("联系验证服务器出错。");
            }
        }
        public static async Task<string> GetAccessTokenAsync(string clientId, string clientSecret, string userName, string password)
        {
            #region 获取AccessToken

            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Basic",
                Convert.ToBase64String(Encoding.UTF8.GetBytes(clientId + ":" + clientSecret)));

            var postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("grant_type", "password"));
            postData.Add(new KeyValuePair<string, string>("UserName", userName));
            postData.Add(new KeyValuePair<string, string>("Password", password));
            HttpContent content = new FormUrlEncodedContent(postData);
             

            HttpResponseMessage response = await httpClient.PostAsync("http://serv.abc.com/oauth2/token", content);

            var formcontent = await response.Content.ReadAsStringAsync();
            try
            {
                var result = JsonConvert.DeserializeObject<CallBackResult>(formcontent);
                if (!string.IsNullOrEmpty(result.Error))
                {
                    throw new NotImplementedException(result.Error);
                }

                if (string.IsNullOrEmpty(result.AccessToken))
                {
                    throw new NotImplementedException("没有获取得到 AccessToken。");
                }



                #endregion

                return result.AccessToken;
            }
            catch
            {
                throw new Exception(formcontent);
            }
        }
    }
}
